package com.example.springsecuritystart.config;

import com.example.springsecuritystart.handler.MyAuthenticationFailureHandler;
import com.example.springsecuritystart.handler.MyAuthenticationSuccessHandler;
import com.example.springsecuritystart.handler.MyLogoutSuccessHandler;
import com.example.springsecuritystart.services.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    MyUserDetailService myUserDetailService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/mylogin.html")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/index")
//                .successForwardUrl("/index")
//                .successHandler(successHandler())
//                .successHandler(new MyAuthenticationSuccessHandler())
//                .failureUrl("/mylogin.html")
//                .failureForwardUrl("/mylogin.html")
//                .failureHandler(failureHandler())
                .failureHandler(new MyAuthenticationFailureHandler())
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .logout()
//                .logoutUrl("/logout")
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout1", "GET"),
                        new AntPathRequestMatcher("/logout2", "POST")))
                .invalidateHttpSession(true)
                .clearAuthentication(true)
//                .logoutSuccessUrl("/mylogin.html")
                .logoutSuccessHandler(new MyLogoutSuccessHandler("logout1"))
                .defaultLogoutSuccessHandlerFor(new MyLogoutSuccessHandler(),
                        new AntPathRequestMatcher("/logout1", "GET"))
                .defaultLogoutSuccessHandlerFor(new MyLogoutSuccessHandler("logout2"),
                        new AntPathRequestMatcher("/logout2", "POST"))
                .and()
                .requiresChannel()
                .antMatchers("/https").requiresSecure()
                .antMatchers("/http").requiresInsecure()
                .and()
                .csrf().disable();
    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("javaboy").password("{noop}123").roles("admin").build());
//        manager.createUser(User.withUsername("ma").password("{noop}123").roles("user").build());
//        auth.userDetailsService(manager);
//    }


//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);
//        if (!manager.userExists("javaboy")) {
//            manager.createUser(User.withUsername("javaboy").password("{noop}123").roles("admin").build());
//        }
//        if (!manager.userExists("ma")) {
//            manager.createUser(User.withUsername("ma").password("{noop}123").roles("user").build());
//        }
//        auth.userDetailsService(manager);
//    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService);
    }

    SavedRequestAwareAuthenticationSuccessHandler successHandler() {
        SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
        handler.setDefaultTargetUrl("/index");
        handler.setTargetUrlParameter("target");
        return handler;
    }

    SimpleUrlAuthenticationFailureHandler failureHandler() {
        SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler("/mylogin.html");
        handler.setUseForward(true);
        return handler;
    }
}
